<script>
  export default {
    name: 'CommonSelect',
    components: {},
    data() {
      return {
        visible: false, // 当前下拉框显隐状态
        renderId: 'common-container', // 传送到的目标元素id
        modelValue: '',
        isObjectValue: false, // 绑定的值类型是否为对象
        opsData: [],

        curInstance: null, // 当前绑定在使用公用组件的实例
        attrs: {},
        isMounted: false,
      };
    },
    computed() {},
    mounted() {
      this.isMounted = true;
    },
    methods: {
      change(val) {
        // // console.log(val)
        // this.modelValue = val
        this.curInstance.updateValue(val);
      },
      blur() {
        // console.log('select-blur')
        this.visible = this.$refs.CommonSelect.visible;
      },
      resetAttr() {
        this.renderId = 'common-container';
        this.curInstance = null;
        this.opsData = [];
        this.isObjectValue = false;
        this.modelValue = '';
        this.attrs = {};
      },
      async toggleMenu({ renderId, curInstance, attrs, curValue, isObjectValue, opsData }) {
        // 重复点击做处理
        if (this.renderId === renderId) {
          if (this.visible) {
            this.visible = false;
            return;
          }
        }
        // this.resetAttr()
        // console.log('opsData',opsData)
        // console.log('attrs',attrs)

        this.attrs = attrs;
        this.isObjectValue = isObjectValue;
        this.modelValue = curValue;
        this.opsData = opsData;
        this.renderId = renderId;
        this.curInstance = curInstance;

        await this.$nextTick();
        this.$refs.CommonSelect.toggleMenu();
      },
    },
  };
</script>

<template>
  <Teleport v-if="isMounted" :to="`#${renderId}`">
    <el-select
      ref="CommonSelect"
      v-bind="attrs"
      :key="renderId"
      v-model="modelValue"
      class="common-select"
      @change="change"
      @blur="blur"
    >
      <el-option
        v-for="item in opsData"
        :key="item.id"
        :label="item[attrs['label-key']]"
        :value="isObjectValue ? item : item[attrs['value-key']]"
      />
    </el-select>
  </Teleport>
</template>

<style lang="scss"></style>
